package cn.java79.quiz.web;

import cn.java79.quiz.entity.Questions;
import cn.java79.quiz.pojo.AjaxPage;
import cn.java79.quiz.pojo.Section;
import cn.java79.quiz.service.QuestionsService;
import cn.java79.quiz.service.SectionService;
import cn.java79.quiz.util.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("*.ques")
public class QuestionsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 5);
        try {
            Method m = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            m.invoke(this, resp, req);
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(501, "服务器出现了错误" + e);
        }
    }

    //显示所有的请求头
    public void showheader(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        //获取请求头信息
        Enumeration<String> headerNames = request.getHeaderNames();
        //使用循环遍历请求头，并通过getHeader()方法获取一个指定名称的头字段
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            out.println(headerName + " : " + request.getHeader(headerName) + "<br/>");
        }
    }

    public void search(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String title = req.getParameter("title");
        String sectionname = req.getParameter("sectionname");

        int pageNo = StrUtil.toInt(req.getParameter("pageNo"), 1);
        AjaxPage<Questions> page = QuestionsService.ME.search(title, sectionname, pageNo, QuestionsService.PAGESIZE);
        //数据怎么带过去
        req.setAttribute("p", page);
        req.setAttribute("title", title);
        req.setAttribute("sectionname", sectionname);
        //req.removeAttribute();
        req.getRequestDispatcher("/WEB-INF/jsps/questions.jsp").forward(req, resp);
    }

    public void show(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long id = StrUtil.toLong(req.getParameter("id"));
        req.setAttribute("q", QuestionsService.ME.get(id));
        req.getRequestDispatcher("/WEB-INF/jsps/question.jsp").forward(req, resp);
    }

    //修改的第一步，展现数据
    public void toUpdate(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long id = StrUtil.toLong(req.getParameter("id"));
        req.setAttribute("q", QuestionsService.ME.get(id));
        //文本值好处理，下拉框，单选，多选麻烦
        //形成下拉框，好选中
        req.setAttribute("sections", SectionService.ME.findTop());
        req.getRequestDispatcher("/WEB-INF/jsps/questionUpdate.jsp").forward(req, resp);
    }

    public void del(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
//        if(req.getSession().getAttribute("USER_LOGIN")==null){
//            resp.getWriter().println("你没有登录");
//            return;
//        }
        long id = StrUtil.toLong(req.getParameter("id"));
        QuestionsService.ME.delete(id);
        req.getSession().setAttribute("msg", "删除成功");
        resp.sendRedirect("search.ques");
    }

    public void toAdd(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        req.setAttribute("sections", SectionService.ME.findTop());
        req.getRequestDispatcher("/WEB-INF/jsps/addques.jsp").forward(req, resp);
    }

    public void add(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException, FileUploadException {
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        Questions q = new Questions();
        q.setCreatedate(new Date());
        int op = 0;

        List<String> options = new ArrayList<>();
        for (FileItem f : fileItems) {

            if (f.isFormField()) {//表单域
                switch (f.getFieldName()) {
                    case "title":
                        q.setTitle(f.getString("utf-8"));
                        break;
                    case "options":
                        //sb.append(f.getString("utf-8"));
                        options.add(f.getString("utf-8"));
                        break;
                    case "degree":
                        q.setDegree(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "answers":
                        //追加
                        q.setAnswers(q.getAnswers() + f.getString("utf-8") + ",");
                        break;
                    case "difficulty":
                        q.setDifficulty(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "weight":
                        q.setWeight(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "examskillid":
                        q.setExamskillid(StrUtil.toLong(f.getString("utf-8")));
                        break;
                    case "questionanalysis":
                        q.setQuestionanalysis(f.getString("utf-8"));
                        break;
                }
            } else {
                if (f.getSize() < 1)
                    continue;
                q.setPicture(f.get());
            }


        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < options.size(); i++) {
            sb.append(i + ":");
            sb.append(options.get(i));
            sb.append("@!@");
        }
        q.setContent(sb.toString());
        //减去最后的逗号
        q.setAnswers(q.getAnswers().substring(0, q.getAnswers().length() - 1));
        int res = QuestionsService.ME.insert(q);
        if (res > 0)
            resp.sendRedirect("search.ques");
        else
            resp.getWriter().println("<script>alert('增加失败！');history.back();</script>");
    }

    public void update(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException, FileUploadException {
        ///long start=System.nanoTime();
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        Questions q = new Questions();
        q.setCreatedate(new Date());
        int op = 0;

        List<String> options = new ArrayList<>();
        for (FileItem f : fileItems) {

            if (f.isFormField()) {//表单域
                switch (f.getFieldName()) {
                    case "id":
                        q.setId(StrUtil.toLong(f.getString("utf-8")));
                        break;
                    case "title":
                        q.setTitle(f.getString("utf-8"));
                        break;
                    case "options":
                        //sb.append(f.getString("utf-8"));
                        options.add(f.getString("utf-8"));
                        break;
                    case "degree":
                        q.setDegree(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "answers":
                        //追加
                        q.setAnswers(q.getAnswers() + f.getString("utf-8") + ",");
                        break;
                    case "difficulty":
                        q.setDifficulty(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "weight":
                        q.setWeight(Short.parseShort(f.getString("utf-8")));
                        break;
                    case "examskillid":
                        q.setExamskillid(StrUtil.toLong(f.getString("utf-8")));
                        break;
                    case "questionanalysis":
                        q.setQuestionanalysis(f.getString("utf-8"));
                        break;
                }
            } else {
                if (f.getSize() < 1)
                    continue;

                q.setPicture(f.get());
            }


        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < options.size(); i++) {
            sb.append(i + ":");
            sb.append(options.get(i));
            sb.append("@!@");
        }
        q.setContent(sb.toString());
        //减去最后的逗号
        q.setAnswers(q.getAnswers().substring(0, q.getAnswers().length() - 1));
        int res = QuestionsService.ME.update(q);
        if (res > 0) {
            //信息放入session,重定向也能显示；
            //显示后要删除。。。
            request.getSession().setAttribute("msg", "修改成功");
            resp.sendRedirect("search.ques");
        } else
            resp.getWriter().println("<script>alert('增加失败！');history.back();</script>");

//        long end=System.nanoTime();
//        long time=end-start;
    }

    public void vcode(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException, FileUploadException {
        //>>resp.reset();

        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200,155,255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length,index;
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<4;i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
            g.drawString(ch[index]+"", (i*15)+3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString()+" "+System.currentTimeMillis());
        ImageIO.write(bi, "JPG", resp.getOutputStream());
    }

}
